package sapling.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

/**
 * Created by mac on 17/2/9.
 */
public class FileUtil {
    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    @Value("${web.upload-path}")
    private static String imgdir="file";

  /*  public static String getFileDateDir(){
        Calendar date= Calendar.getInstance();
        SimpleDateFormat format1=new SimpleDateFormat( "yyyy ");
        SimpleDateFormat format2=new SimpleDateFormat( "MM ");
        SimpleDateFormat format3=new SimpleDateFormat( "dd ");
        String name1=format1.format(date.getTime());
        String name2=format2.format(date.getTime());
        String name3=format3.format(date.getTime());
        return name1+ File.separator+name2+File.separator+name3+File.separator;
    }*/

    public static String savefile(MultipartFile file){
        String imgUrl="";
        if(file!=null){
            if(!file.isEmpty()){
                String str = file.getOriginalFilename();
                String str2 = str.replaceAll(" ", "");
                String str3= str2.replace("\\", "");
                String filename =new Date().getTime()+"_"+str3;
                File dir=new File(imgdir);
                if(!dir.exists()) {
                    dir.mkdirs();
                }
                try {
                    FileOutputStream out1 = new FileOutputStream(new File(dir.getPath(), filename));
                    BufferedOutputStream out = new BufferedOutputStream(out1);
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    log.info("上传失败,"+e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    log.info("上传失败,"+e.getMessage());
                }
               log.info(imgUrl=filename);
            }else{
                log.info("上传失败，文件为空");
            }
        }
       return imgUrl;
    }
}
